package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    //注入RedisTemplate对象，用户操作redis
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发短信
     * @param user
     * @param session
     * @return
     */
    @RequestMapping("sendMsg")
    public R<String>sendMsg(@RequestBody User user, HttpSession session){//参数为什么要用user来接

        //1.获取手机号码
        String phone = user.getPhone();
        //2.生成四位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("=============本次验证码：==============="+code);


        //session.setAttribute(phone,code);
        ValueOperations operations = redisTemplate.opsForValue();
        //验证码存储到redis中，并且设置过去时间为5分钟
        operations.set(phone,code,5, TimeUnit.MINUTES);
        return R.success("");
    }

    /**
     * 登录验证
     * @param param
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String,String>param,HttpSession session){

        //1.取出数据
        String phone = param.get("phone");
        String code = param.get("code");//用户输入的验证码
       // String codeInSession = (String) session.getAttribute(phone);//系统生成的验证码
        String codeInSession= (String) redisTemplate.opsForValue().get(phone);
        User loginUser = userService.login(phone, code, codeInSession);
        if (loginUser!=null){
            //登录成功,把登录的用户存到session中
            session.setAttribute("user",loginUser.getId());
           //删除验证码
            redisTemplate.delete(phone);

        }else {
            return R.error("登录失败，请重试");
        }
        return R.success(loginUser);
    }




}
